<template>
  <div style="width: 50%; margin: 10px auto">
    <div class="card">
      <el-form label-width="100px" style="padding-right: 50px" :model="form" :rules="rules" ref="formRef">
        <el-form-item prop="name" label="名称">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item prop="category" label="分类">
          <el-select v-model="form.category" style="width: 100%">
            <el-option v-for="item in categoryList" :key="item.id" :value="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="tags" label="标签">
          <el-select v-model="form.tags" style="width: 100%" multiple>
            <el-option v-for="item in tagList" :key="item.id" :value="item.name" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              :action="$baseUrl + '/files/upload'"
              :headers="{ token: user.token }"
              list-type="picture"
              :on-success="handleCoverSuccess"
          >
            <el-button type="primary">上传封面</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="descr" label="作品简介">
          <el-input type="textarea" v-model="form.descr" autocomplete="off" placeholder="请输入作品简介"></el-input>
        </el-form-item>
        <el-form-item prop="author" label="作者简介">
          <el-input type="textarea" v-model="form.author" autocomplete="off" placeholder="请输入作者简介"></el-input>
        </el-form-item>
        <el-form-item prop="background" label="创作背景">
          <el-input type="textarea" v-model="form.background" autocomplete="off"
                    placeholder="请输入创作背景"></el-input>
        </el-form-item>
        <el-form-item label="作品内容">
          <div style="display: flex; align-items: center; margin-bottom: 5px" v-for="(item, index) in contentList"
               :key="index">
            <el-upload
                :action="$baseUrl + '/files/upload'"
                :headers="{ token: user.token }"
                :on-success="(response, file, fileList) => handleStepImgSuccess(response, file, fileList, item)"
                :show-file-list="false"
            >
              <img v-if="item.img" :src="item.img" alt="" style="width: 50px; height: 50px">
              <el-button v-else type="primary">上传图片</el-button>
            </el-upload>
            <el-input type="textarea" style="flex: 1;  margin-left: 10px" v-model="item.text"
                      placeholder="请填写作品内容"></el-input>
            <i @click="delContent(index)" class="el-icon-delete" style="margin-left: 10px; cursor: pointer"></i>
          </div>
          <div><span style="color: #2a60c9; font-size: 14px; cursor: pointer"
                     @click="addContent">添加新的作品内容</span></div>
        </el-form-item>
        <el-form-item label="人物介绍">
          <div style="display: flex; align-items: center; margin-bottom: 5px" v-for="(item, index) in characterList"
               :key="index">
            <el-input style="flex: 0.5;" v-model="item.name" placeholder="请输入人物名称"></el-input>
            <el-input type="textarea" style="flex: 1.5;  margin-left: 10px" v-model="item.text"
                      placeholder="请输入人物简介"></el-input>
            <i @click="delCharacter(index)" class="el-icon-delete" style="margin-left: 10px; cursor: pointer"></i>
          </div>
          <div><span style="color: #2a60c9; font-size: 14px; cursor: pointer" @click="addCharacter">添加新的人物</span>
          </div>
        </el-form-item>
        <el-form-item label="作品赏析">
          <div style="display: flex; align-items: center; margin-bottom: 5px" v-for="(item, index) in appreciationList"
               :key="index">
            <el-input style="flex: 0.5;" v-model="item.name" placeholder="请输入赏析角度"></el-input>
            <el-input type="textarea" style="flex: 1.5;  margin-left: 10px" v-model="item.text"
                      placeholder="请输入赏析内容"></el-input>
            <i @click="delAppreciation(index)" class="el-icon-delete" style="margin-left: 10px; cursor: pointer"></i>
          </div>
          <div><span style="color: #2a60c9; font-size: 14px; cursor: pointer"
                     @click="addAppreciation">添加新的赏析内容</span></div>
        </el-form-item>
        <el-form-item prop="effect" label="作品影响">
          <el-input type="textarea" v-model="form.effect" autocomplete="off"
                    placeholder="请输入作品造成影响"></el-input>
        </el-form-item>
        <el-form-item label="作品资讯">
          <div style="display: flex; align-items: center; margin-bottom: 5px" v-for="(item, index) in infoList"
               :key="index">
            <el-date-picker
                v-model="item.time"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
            </el-date-picker>
            <el-input type="textarea" style="flex: 1.5;  margin-left: 10px" v-model="item.text"
                      placeholder="请输入赏析内容"></el-input>
            <i @click="delInfo(index)" class="el-icon-delete" style="margin-left: 10px; cursor: pointer"></i>
          </div>
          <div><span style="color: #2a60c9; font-size: 14px; cursor: pointer"
                     @click="addInfo">添加新的作品资讯</span></div>
        </el-form-item>
        <el-form-item prop="publishTime" label="发版时间">
          <el-date-picker
              v-model="form.publishTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div style="text-align: center; margin-top: 20px">
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "AddWorks",
  data() {
    return {
      id: this.$route.query.id,
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      categoryList: [],
      tagList: [],
      form: {},
      rules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
        ],
        category: [
          {required: true, message: '请选择分类', trigger: 'blur'},
        ],
        descr: [
          {required: true, message: '请输入作品简介', trigger: 'blur'},
        ],
        background: [
          {required: true, message: '请输入创作背景', trigger: 'blur'},
        ],
        author: [
          {required: true, message: '请输入作者简介', trigger: 'blur'}
        ],
        effect: [
          {required: true, message: '请输入作品影响', trigger: 'blur'}
        ]
      },
      characterList: [],
      appreciationList: [],
      contentList: [],
      infoList: [],
    }
  },
  created() {
    this.loadCategory()
    this.load()
    this.loadTag()
  },
  methods: {
    load() {
      if (this.id) {
        this.$request.get('/works/selectById/' + this.id).then(res => {
          this.form = res.data || {}
          this.characterList = JSON.parse(this.form.chara || '[]')  // JSON.parse解析json字符串
          this.contentList = JSON.parse(this.form.content || '[]')
          this.appreciationList = JSON.parse(this.form.appreciation || '[]')
          this.infoList = JSON.parse(this.form.workInfo || '[]')
          this.form.tags=JSON.parse(this.form.tags||'[]')
        })
      }
    },
    save() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if (!this.contentList.length) {
            this.$message.warning('作品内容不能为空')
            return
          }
          this.form.chara = JSON.stringify(this.characterList) // 把json数组转成json字符串存到数据库
          this.form.content = JSON.stringify(this.contentList)
          this.form.appreciation = JSON.stringify(this.appreciationList)
          this.form.workInfo = JSON.stringify(this.infoList)
          this.form.tags = JSON.stringify(this.form.tags)
          this.form.userId = this.user.id
          if (this.form.id) {
            this.$request.put('/works/update', this.form).then(res => {
              if (res.code === '200') {   // 表示操作成功
                this.$message.success('操作成功')
                setTimeout(() => {
                  location.href = '/front/workDetail?id=' + this.id
                }, 500)
              } else {
                this.$message.error(res.msg)  // 弹出错误的信息
              }
            })
          } else {
            this.$request.post('/works/add', this.form).then(res => {
              if (res.code === '200') { // 表示操作成功
                this.$message.success('操作成功')
                setTimeout(() => {
                  location.href = '/front/userWorks';
                }, 500)
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    },
    delContent(index) {
      this.contentList.splice(index, 1)
    },
    addContent() {
      this.contentList.push({img: '', text: ''})
    },
    delCharacter(index) {
      this.characterList.splice(index, 1)
    },
    addCharacter() {
      this.characterList.push({name: '', text: ''})
    },
    delAppreciation(index) {
      this.appreciationList.splice(index, 1)
    },
    addAppreciation() {
      this.appreciationList.push({name: '', text: ''})
    },
    delInfo(index) {
      this.infoList.splice(index, 1)
    },
    addInfo() {
      this.infoList.push({time: '', text: ''})
    },
    loadCategory() {
      this.$request.get('/category/selectAll').then(res => {
        this.categoryList = res.data || []
      })
    },
    handleCoverSuccess(res) {
      this.form.cover = res.data
    },
    handleStepImgSuccess(response, file, fileList, item) {
      item.img = response.data
      this.$message.success("上传图片成功")
    },
    loadTag() {
      this.$request.get('/tag/selectAll').then(res => {
        this.tagList = res.data || []
      })
    },
  }
}
</script>

<style scoped>

</style>